object Sheet14 extends App {
  //  val ch = '9'
  //  var sign, digit: Int = 0
  //  ch match {
  //    case _ if Character.isDigit(ch) => digit = Character.digit(ch, 10)
  //    case '+' => sign = 1
  //    case '-' => sign = -1
  //    case _ => sign = 0
  //  }

  //  val ch = '9'
  //  var sign, digit: Int = 0
  //  ch match {
  //    case ch2 => digit = Character.digit(ch2, 10)
  //    case '+' => sign = 1
  //    case '-' => sign = -1
  //    case _ => sign = 0
  //  }
  //
  //  println(s"$digit, $sign")

  val arr = Array(0, 1, 3, 3, 3)
  val result1 = arr match {
    case Array(0) => "0"
    case Array(x, y) => s"$x $y"
    case Array(0, rest@_*) => rest.min
    case _ => "something else"
  }

  println(result1)

  val lst = List(3, 2, 4)
  val result2 = lst match {
    case 0 :: Nil => "0"
    case x :: y :: Nil => s"$x, $y" // Nil 表示就这么多
    case 0 :: tail => "0 ... " + tail
    case _ => "something else"
  }

  println(result2)


  //  val pair = (1, 0)
  //  val result3 = pair match {
  //    case (_, 0) | (0, _) => 0 // OK, matches if one component is zero
  //    case (x, 0) | (0, x) => x // Error—cannot bind with alternatives
  //  }
  //  println(result3)

  val pattern = "([0-9]+) ([a-z]+)".r
  val result4 = "99 bottles" match {
    case pattern(num, item) => num + item
    // Sets num to "99", item to "bottles"
  }

  println(result4)


  val (q, r) = BigInt(10) /% 3
  println(q, r)

//  val x = 3
//  val 2 = x

  val it: Item = Bundle("Father's day special", 20.0,
    Article("Scala for the Impatient", 39.95),
    Bundle("Anchor Distillery Sampler", 10.0,
      Article("Old Potrero Straight Rye Whiskey", 79.95),
      Article("Junípero Gin", 32.95)
    )
  )

  val result5 = it match {
    case Bundle(_, _, art @ Article(_, _), rest @ _*) => s" ${art.description}, ${art.price}, $rest"
  }
  println(result5)

  def price(it: Item): Double = it match {
    case Article(_, p) => p
    case Bundle(_, disc, its @ _*) => its.map(price).sum - disc
  }

  println(price(it))

  val result6 = "+3-4".collect { case '+' => 1 ; case '-' => -1 }
  println(result6)

  val varPattern = """\{([0-9]+)\}""".r
  val message = "At {1}, there was {2} on {0}"
  val vars = Map("{0}" -> "planet 7", "{1}" -> "12:30 pm",
    "{2}" -> "a disturbance of the force.")
  val result7 = varPattern.replaceSomeIn(message, m => vars.lift(m.matched))
  println(result7)

  println(vars.lift)
  println(vars.lift("{0}"))
}

abstract class Item
case class Article(description: String, price: Double) extends Item
case class Bundle(description: String, discount: Double, items: Item*) extends Item
